package com.sci.controller;


import com.sci.entity.Business;
import com.sci.entity.CommonResult;
import com.sci.entity.Order;
import com.sci.entity.User;
import com.sci.feign.UserServiceFeign;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("order")
public class OrderController {

    //    @Resource
//    private RestTemplate restTemplate;
    @Resource
    private UserServiceFeign userServiceFeign;

    @GetMapping("/testGet/{orderId}")
    // 使用A断路器，如果调用失败，则调用downServiceA方法
    @Bulkhead(name = "myBulkhead", fallbackMethod = "downService")
    public CommonResult<Order> getOrder(@PathVariable(value = "orderId") String orderId) {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setPrice(66.6);
        User user = userServiceFeign.getUser(101);
        order.setUser(user);
        Integer code = 200;
        String message = "success";
        CommonResult<Order> commonResult = new CommonResult<>();

        commonResult.setCode(code);
        commonResult.setMessage(message);
        commonResult.setResult(order);
        System.out.println("Success!");
        return commonResult;
    }

    public CommonResult<Order> downService(String orderId, Throwable e) {
        e.printStackTrace();
        String message = "获取订单" + orderId + "信息的服务当前超时，因此方法降级";
        System.out.println(message);
        CommonResult<Order> result = new CommonResult<>(400, message, new Order());
        return result;
    }


    // POST: 创建订单
    @PostMapping("/testPost/{orderId}")
    @CircuitBreaker(name = "B", fallbackMethod = "downServiceB")
    public CommonResult<Order> createOrder(@PathVariable(value = "orderId") String orderId) {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setPrice(66.6);
        User user = userServiceFeign.getUser(101);
        order.setUser(user);
        Integer code = 200;
        String message = "success";

        CommonResult<Order> commonResult = new CommonResult<>();
        commonResult.setCode(code);
        commonResult.setMessage(message);
        commonResult.setResult(order);
        System.out.println("Success!");
        return commonResult;
    }

    public CommonResult<Order> downServiceB(String orderId, Throwable e) {
        e.printStackTrace();
        String message = "创建订单" + orderId + "信息的服务当前超时，因此方法降级";
        System.out.println(message);
        CommonResult<Order> result = new CommonResult<>(400, message, new Order());
        return result;
    }
}